package com.kangjia.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;

import com.fasterxml.jackson.databind.JsonNode;
import com.kangjia.holder.VariableThreadLocal;
import com.kangjia.jasckson.DataMapper;
import com.kangjia.response.ErrorResponse;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Order(1)
@Slf4j
public class LoginFilter implements Filter {

	private JedisPool jedisPool;
	
	public LoginFilter(JedisPool jedisPool) {
		super();
		this.jedisPool = jedisPool;
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		log.info("url={},请求方法={}", request.getRequestURI(), request.getMethod());
		if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}
		String encrypt = request.getHeader("HWBK");
		if (StringUtils.isBlank(encrypt)) {
			response.getOutputStream().write(DataMapper.getInstance().writeValueAsBytes(new ErrorResponse("未登陆")));
		} else {	
			Jedis jedis = jedisPool.getResource();
			String json = null;
			try {
				json = jedis.get(encrypt);
				if (StringUtils.isNotBlank(json)) {					
					jedis.expire(encrypt, 3600);
				} else {
					log.error("系统访问标识错误 json={}", json);
					jedis.del(encrypt);
				}
			} finally {
				jedis.close();
			}
			if (StringUtils.isBlank(json)) {
				response.getOutputStream().write(DataMapper.getInstance().writeValueAsBytes(new ErrorResponse("未登陆")));
				return;
			}
			JsonNode jsonNode = DataMapper.getInstance().readTree(json);
			VariableThreadLocal.set("login", jsonNode);
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	public void destroy() {
	}
}
